/**
 * ChatGPT.vue - ChatGPT聊天组件
 * 提供与后端API的聊天界面
 */

<script setup>

import { defineOptions } from 'vue'

defineOptions({
    name: 'ChatGPT'
})

import { ref,onMounted,nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { ChatDotRound,ChatLineRound,Service,User,Position,Loading } from '@element-plus/icons-vue';  //必须重复显式导入
import { sendMessage as sendOpenAIMessage,createUserMessage,createAssistantMessage } from '../services/openaiService';
// import { sendMessage as sendXAIMessage } from '../services/xaiService';

// 组件状态
const messages=ref([]); // 聊天消息历史
const inputMessage=ref(''); // 用户输入
const loading=ref(false); // 加载状态
const messageContainerRef=ref(null); // 消息容器引用
const chatTopic=ref(''); // 当前聊天主题
const currentApiType=ref('openai'); // 当前使用的API类型



// 在 ChatGPT.vue 中添加
import { onActivated,onDeactivated } from 'vue';

// 组件被激活时触发
onActivated(() => {
    console.log('ChatGPT Component activated');
    nextTick(() => {
        if(messageContainerRef.value) {
            messageContainerRef.value.scrollTop=messageContainerRef.value.scrollHeight;
        }
    });
});

// 组件被停用时触发
onDeactivated(() => {
    console.log('Component deactivated');
    // 可以在这里处理一些停用时的逻辑
});

// 添加延迟函数
const delay=(ms) => new Promise(resolve => setTimeout(resolve,ms));

/**
 * 发送消息到后端API
 * @param {string} content - 用户输入的消息内容
 */
const handleSendMessage=async (content) => {
    if(!content.trim()||loading.value) return;

    try {
        loading.value=true;

        // 添加1秒延迟
        await delay(1000);

        // 添加用户消息
        const userMessage=createUserMessage(content);
        messages.value.push(userMessage);

        // 更新聊天主题
        if(messages.value.length===1) {
            chatTopic.value=content.slice(0,10)+(content.length>10? '...':'');
        }

        // 发送消息到对应的API
        const response=await (currentApiType.value==='openai'?
            sendOpenAIMessage(content):
            sendXAIMessage(content));

        // 检查是否有错误
        if(response.error) {
            ElMessage({
                message: response.message,
                type: response.error.type||response.type||'error',
                duration: 5000
            });
            // 移除失败的消息
            messages.value.pop();
            return;
        }

        // 添加AI回复
        if(response&&response.choices&&response.choices[0]) {
            messages.value.push(createAssistantMessage(response.choices[0].message.content));
        } else {
            ElMessage({
                message: '无效的API响应',
                type: response.type||response.error.type||'error',
                duration: 5000
            });
            messages.value.pop();
        }

        // 清空输入框
        inputMessage.value='';

        // 滚动到底部
        await nextTick();
        scrollToBottom();
    } catch(error) {
        console.error('发送消息错误:',error);
        ElMessage({
            message: error.message||'发送消息失败，请重试',
            type: error.message.type||error.type||'error',
            duration: 5000  // 显示5秒
        });
        // 移除失败的消息
        messages.value.pop();
    } finally {
        loading.value=false;
    }
};

/**
 * 切换API类型
 */
const toggleApiType=() => {
    currentApiType.value=currentApiType.value==='openai'? 'xai':'openai';
    ElMessage.success(`已切换到 ${currentApiType.value.toUpperCase()} 模式`);
};

/**
 * 处理键盘事件
 * @param {Event} event - 键盘事件对象
 */
const handleKeyPress=(event) => {
    if(event.key==='Enter'&&!event.shiftKey) {
        event.preventDefault();
        handleSendMessage(inputMessage.value);
    }
};

/**
 * 滚动消息容器到底部
 */
const scrollToBottom=() => {
    if(messageContainerRef.value) {
        messageContainerRef.value.scrollTop=messageContainerRef.value.scrollHeight;
    }
};

// 组件挂载时初始化
onMounted(() => {
    if(messageContainerRef.value) {
        messageContainerRef.value.scrollTop=messageContainerRef.value.scrollHeight;
    }
});
</script>

<template>
    <div class="chat-container">
        <!-- 聊天主题 -->
        <div v-if="chatTopic" class="chat-topic">
            <el-icon>
                <ChatDotRound />
            </el-icon>
            <span>当前话题: {{ chatTopic }}</span>
            <el-button type="text" size="small" @click="toggleApiType" class="api-toggle">
                当前模式: {{ currentApiType.toUpperCase() }}
            </el-button>
        </div>

        <!-- 消息列表 -->
        <div ref="messageContainerRef" class="message-container">
            <template v-if="messages.length === 0">
                <div class="welcome-message">
                    <el-icon class="service-icon">
                        <Service />
                    </el-icon>
                    <h2>欢迎使用AI助手 chatgpt-3.5-turbo ·免开VPN</h2>
                    <p>我可以帮助你回答问题、编写代码、解决问题等。</p>
                    <p>当前使用的是 {{ currentApiType.toUpperCase() }} 模式</p>
                    <p>点击右上角可以切换模式</p>
                    <p>请在下方输入你的问题，按Enter发送。</p>
                </div>
            </template>
            <template v-else>
                <div v-for="(message, index) in messages" :key="index" :class="['message', message.role === 'user' ? 'user-message' : 'ai-message']">
                    <div class="message-avatar">
                        <el-icon :size="36">

                            <!-- <component :is="message.role === 'user' ? User : message.role === 'assistant' ? Service : null" /> -->
                            <component :is="message.role === 'user' ? 'User' : message.role === 'assistant' ? 'Service' : null" />
                        </el-icon>
                    </div>
                    <div class="message-content">
                        <div class="message-text">{{ message.content }}</div>
                        <div class="message-time">{{ new Date().toLocaleTimeString() }}</div>
                    </div>
                </div>
            </template>
        </div>

        <!-- 输入区域 -->
        <div class="input-container">
            <el-input v-model="inputMessage" type="textarea" :rows="3" :placeholder="loading ? '正在思考中...' : '输入消息，按Enter发送，Shift+Enter换行'" @keydown="handleKeyPress" :disabled="loading" resize="none">
                <template #prefix>
                    <el-icon>
                        <ChatLineRound />
                    </el-icon>
                </template>
            </el-input>
            <el-button type="primary" @click="handleSendMessage(inputMessage)" :loading="loading" :disabled="!inputMessage.trim() || loading">
                <el-icon v-if="!loading">
                    <Position />
                </el-icon>
                <el-icon v-else>
                    <Loading />
                </el-icon>
                <span>{{ loading ? '思考中...' : '发送' }}</span>
            </el-button>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.chat-container {
    display: flex;
    flex-direction: column;
    height: 95%;
    max-height: calc(100% - 20px);
    padding: 1rem;
    gap: 1rem;
    // max-width: 800px;
    margin: 0 auto;
    margin-top: 10px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.chat-topic {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 0.5rem 1rem;
    background-color: #f5f7fa;
    border-radius: 4px;
    font-size: 0.9rem;
    color: #606266;
}

.api-toggle {
    margin-left: auto;
    color: #409eff;
}

.message-container {
    flex: 1;
    overflow-y: auto;
    padding: 1rem;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background-color: #fff;
    margin-bottom: 0px;
}

.welcome-message {
    text-align: center;
    padding: 2rem;
    color: #606266;
}

.welcome-message h2 {
    margin: 1rem 0;
    color: #303133;
}

.welcome-message p {
    margin: 0.5rem 0;
    color: #909399;
}

.message {
    display: flex;
    gap: 1rem;
    margin-bottom: 1.5rem;
    max-width: 85%;
}

.user-message {
    margin-left: auto;
    flex-direction: row-reverse;
}

.ai-message {
    margin-right: auto;
}

.message-avatar {
    flex-shrink: 0;
}

.message-content {
    display: flex;
    flex-direction: column;
    gap: 4px;
    padding: 0 5px;
    font-size: 12px;
}

.message-text {
    padding: 0.8rem 1rem;
    border-radius: 8px;
    line-height: 1.5;
    white-space: pre-wrap;
    font-size: 12px;
}

.user-message .message-text {
    background-color: #409eff;
    color: white;
}

.ai-message .message-text {
    background-color: #f5f7fa;
    color: #303133;
}

.message-time {
    font-size: 0.8rem;
    color: #909399;
    text-align: right;
}

.input-container {
    display: flex;
    gap: 1rem;
    align-items: flex-start;
    padding: 1rem;
    background-color: #f5f7fa;
    border-radius: 4px;
}

.input-container :deep(.el-input__wrapper) {
    background-color: #fff;
}

.input-container :deep(.el-textarea__inner) {
    min-height: 60px !important;
    resize: none;
}

.input-container .el-button {
    height: auto;
    max-height: 82px;
    min-height: 40px;
    padding: 0 2rem;
}

/* 滚动条样式 */
.message-container::-webkit-scrollbar {
    width: 6px;
}

.message-container::-webkit-scrollbar-thumb {
    background-color: #dcdfe6;
    border-radius: 3px;
}

.message-container::-webkit-scrollbar-track {
    background-color: #f5f7fa;
}

/* 移动端和竖屏适配 */
@media screen and (max-width: 768px), (orientation: portrait) {
    .chat-container {
        padding: 0;
        height: calc(100vh - 120px);
        margin: 0;
        border-radius: 0;
        box-shadow: none;
    }

    .chat-topic {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        z-index: 100;
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(8px);
        padding: 10px 15px;
        margin: 0;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    }

    .api-toggle {
        position: fixed;
        top: 10px;
        right: 10px;
        z-index: 101;
        background: rgba(255, 255, 255, 0.9);
        backdrop-filter: blur(5px);
        border-radius: 20px;
        padding: 4px 12px;
        font-size: 12px;
    }

    .message-container {
        margin-top: 50px;
        margin-bottom: 70px;
        padding: 10px;
    }

    .input-container {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(8px);
        box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.1);
        padding: 10px;
        margin: 0;
        border-radius: 0;
    }

    .input-container :deep(.el-textarea__inner) {
        min-height: 40px !important;
        padding-right: 90px;
    }

    .input-container .el-button {
        position: absolute;
        right: 10px;
        bottom: 15px;
        min-height: 36px;
        padding: 0 15px;
        font-size: 14px;
    }
}
</style>
